package com.all.proxy.handler;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author LY
 * @create 2024/3/7 13:47
 * @Description 实现jdk动态代理
 */
@Slf4j
public class JdkProxyHandler<T> implements InvocationHandler {

    private Object target;//代理目标类

    public JdkProxyHandler(Object target) { //构造方法
        this.target = target;
    }

    public <T> T getProxy(Class<T> clazz) {
        log.info("基于JDK动态代理...");
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(),
                clazz.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log.info("jdk动态代理|{}|{}|{}", proxy, method, args);
        Object invoke = method.invoke(target, args);
        log.info("代理结束反参|{}", invoke);
        return invoke;
    }
}
